const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
class Promise {
  constructor(executor) {
    this.status = PENDING;
    this.value = undefined;
    this.reason = undefined;
    this.onResolvedCallbacks = []
    this.onRejectedCallbacks = []
    const resolve = (value) => {
      if (this.status === PENDING) {
        this.status = FULFILLED;
        this.value = value;
        this.onResolvedCallbacks.forEach(fn=>fn())
      }
    };
    const reject = (reason) => {
      if (this.status === PENDING) {
        this.status = REJECTED;
        this.reason = reason;
        this.onRejectedCallbacks.forEach(fn=>fn())
      }
    };
    try {
      executor(resolve, reject);
    } catch (e) {
      reject(e);
    }
  }
  then(onFulfilled, onRejected) {
    if(this.status === FULFILLED){
        // ...
        onFulfilled(this.value)
    }
    if(this.status ===  REJECTED){
        // ...
        onRejected(this.reason)
    }
    if(this.status === PENDING){
        // 如果是pending状态，意味着没有更改状态 
        this.onResolvedCallbacks.push(()=>{
            // ...
            onFulfilled(this.value)
        });
        this.onRejectedCallbacks.push(()=>{
            // ...
            onRejected(this.reason)
        })
    }
  }
}
module.exports = Promise;
